unit RequesterThread;

interface

uses
  System.Classes, Requester, sqlexpr, warcommons, sysutils, syncobjs;

type
  TRequesterThread = class(TThread)
  private
    FWaitEvent: TEvent;
    FRequesterId: String;
    FBrokerAddress: String;
  protected
    procedure Execute; override;
  public
    property RequesterId: String read FRequesterId write FRequesterId;
    property BrokerAddress: String read FBrokerAddress write FBrokerAddress;
    constructor Create(ACreateSuspended: Boolean); overload;
    destructor Destroy; override;
  end;

implementation

uses mainRequester;

{ TRequesterThread }
constructor TRequesterThread.Create(ACreateSuspended: Boolean);
begin
  FWaitEvent := TEvent.Create(
    nil,
    True,
    False,
    '');
  inherited;
end;

destructor TRequesterThread.Destroy;
begin
  FWaitEvent.Free;
  inherited;
end;

procedure TRequesterThread.Execute;
var
  GetURLResult: integer;
  mySqlConnection: TSQLConnection;
  WaitResult: TWaitResult;

begin
  mySqlConnection := TSQLConnection.Create(nil);

  mySqlConnection.DriverName := 'Datasnap';
  mySqlConnection.Params.Values['HostName'] := BrokerAddress;
  mySqlConnection.Params.Values['UseUnicode'] := 'True';
  mySqlConnection.LoginPrompt := False;
  logMessage('Connecting to broker');
  try
    try
      mySqlConnection.Connected := True;
      logMessage('Connected to broker');
    except
      on E: Exception do
        logMessage(E.ClassName + ': ' + E.Message);
    end;
    GetURLResult := 0;

    while mySqlConnection.Connected = True do
    begin
      case GetURLResult of
        1:
          begin
            // Queue is empty. Wait for a while...
            logMessage('Queue is empty. Wait for a while...');
            WaitResult := FWaitEvent.WaitFor(300000);
            if WaitResult = wrError then
              logMessage('Error while waiting for something to do : ' +
                IntToStr(FWaitEvent.LastError));
          end;
        503:
          begin
            // Throttled by Blizzard. Wait for a while...
            logMessage('Throttled by Blizzard. Wait for a while...');
            WaitResult := FWaitEvent.WaitFor(300000);
            if WaitResult = wrError then
              logMessage('Error while throttled : ' +
                IntToStr(FWaitEvent.LastError));
          end;
      else
         GetURLResult := GetURLFromQueue(RequesterId, mySqlConnection)
      end;
    end;
    logMessage('Disconnected from broker');
  finally
    mySqlConnection.Free;
  end;
end;

end.
